<?php

namespace app\admin\controller\user;

use app\admin\model\cms\OrderModel;
use app\admin\model\Score;
use app\admin\model\UserGroup;
use app\api\service\HuaWeiSMS;
use app\common\controller\Backend;
use app\common\library\Auth;
use app\common\library\Sms as Smslib;
use app\common\model\Config;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\helper\ArrayHelper;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname,mobile';//表单搜索框允许检索的字段

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('group')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
                //会员组来源
                $v['pay_type'] = 0;
                if ($v['group_id'] != 1) {
                    $v['pay_type'] = OrderModel::where('user_id', $v['id'])
                            ->where('goods_id', $v['group_id'])
                            ->where('goods_type', 'user_group')
                            ->where('pay_status', 1)//1=已经支付
                            ->order('id', 'desc')
                            ->value('pay_type') ?? 0;
                }
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $this->modelValidate = true;
        $groupList = \app\admin\model\UserGroup::where('status', 'normal')->column('id,name');
        $this->view->assign('groupList', $groupList);

        $config = \app\common\model\Config::where('group','basic')->column('name,value');
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        $params['username'] = $params['mobile'];
        $params['status'] = 'audit';
        $params['is_perfect'] = 1;//是否完善信息|0:否,1:是
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $params['nickname'] = $this->model->getRandomnickname();
        $params = $this->preExcludeFields($params);


        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $params['invitation_code'] = $this->model->generateInviteCode();//4位唯一邀请码
        $params['invitation_code_key'] = md5($params['invitation_code']);//4位唯一邀请码MD5加密后的值
        //默认头像
        if (!$params['avatar']) {
            $params['avatar'] = '/img/default_user.jpg';//默认头像
        }

        $user_group = UserGroup::where('id',$params['group_id'])->find();
        if ((float)$user_group['membership_price'] < 0.01){
            $params['period_of_validity'] = 1;
        }else{
            $params['period_of_validity'] = 1;
            if ($user_group['membership_expiry'] > 0){
                $params['period_of_validity'] = (time() + ($user_group['membership_expiry'] * 24 * 60 * 60)) * 1000;
            }
        }

        //验证邮箱是否存在
        if($params['email']){
            $is_email_exist = \app\admin\model\User::where('email',$params['email'])->value('id');
            if($is_email_exist) {
                $this->error('邮箱地址已存在');
            }
        }

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

            $result = $this->model->allowField(true)->save($params);

            //更新用户积分流水记录
            $score = $params['score'] ?? 0;
            $this->scoreChange($this->model->id,$score,true);//更新用户积分流水记录

            // 给插入的用户发送短信
            $sm_msg = "复盘账号已成功开通，请使用本手机号码登录，初始密码为{$params['password']}。如有疑问联系客服请致电{$config['service_tel']}";
            //$ret = Smslib::notice($params['mobile'], $sm_msg);

//            $obj = new HuaWeiSMS();
//            $ret = $obj->send($params['mobile'],[$params['password']],'注册类');
//            if ($ret['code'] != 200) {
//                $this->error('发送失败，请检查短信配置是否正确');
//            }
            Db::commit();
        } catch (ValidateException | PDOException | \Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result == false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
            $request = $this->request->param();

            $user_image_upload_time = Db::name('user')->where('id', $ids)->value('user_image_upload_time');
            if (!$user_image_upload_time && $this->request->post()['row']['user_image']) {
                $this->excludeFields = ['group_id'];
                setMemberTypeByGroup_id($ids, 2);//更新用户信息
            } else {
                setMemberTypeByGroup_id($ids, $this->request->post()['row']['group_id']);//更新用户信息
            }



            $this->request->post()['row']['group_id'] = 2;
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
//        group_id
        $groupList = \app\admin\model\UserGroup::where('status', 'normal')->column('id,name');
        $this->view->assign('groupList', $groupList);

        //编辑更新用户信息
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;

        $user_group = UserGroup::where('id',$params['group_id'])->find();
        if ((float)$user_group['membership_price'] < 0.01){
            $params['period_of_validity'] = 1;
        }else{
            $params['period_of_validity'] = 1;
            if ($user_group['membership_expiry'] > 0){
                $params['period_of_validity'] = (time() + ($user_group['membership_expiry'] * 24 * 60 * 60)) * 1000;
            }
        }

        //验证邮箱是否存在
        if($params['email']){
            $is_email_exist = \app\admin\model\User::where('id','<>',$params['id'])
                ->where('email',$params['email'])->value('id');
            if($is_email_exist) {
                $this->error('邮箱地址已存在');
            }
        }

        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }

            //更新用户积分流水记录
            $score = $request['row']['score'] ?? 0;
            $this->scoreChange($ids,$score,false);//更新用户积分流水记录

            $result = $row->allowField(true)->save($params);

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    //上传用户协议
    public function uploadServiceAgreement()
    {
        if ($this->request->isPost()) {

            $service_agreement = $this->request->post('service_agreement');
            $service_agreement_text = $this->request->post('service_agreement_text');
            Db::name('config')->where('name', 'service_agreement')->update(['value' => $service_agreement]);
            Db::name('config')->where('name', 'service_agreement_text')->update(['value' => $service_agreement_text]);
            $this->success();
        } else {
            $service_agreement = Config::where('name', 'service_agreement')->value('value');
            $service_agreement_text = Config::where('name', 'service_agreement_text')->value('value');
            $this->view->assign("service_agreement", $service_agreement);
            $this->view->assign("service_agreement_text", $service_agreement_text);
        }
        return $this->view->fetch("uploadServiceAgreement");
    }

    /**
     * 积分改变
     * @param $user_id 用户id
     * @param $new_score 改变后的积分
     * @param $is_add_user 是否是添加新用户 true=是 ,false=否(编辑用户)
     * @return Score|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function scoreChange($user_id, $new_score, $is_add_user = false)
    {
        //查询用户原有积分
        $user = \app\admin\model\User::find($user_id);
        $old_score = $user['score'] ?? 0;

        //判断新积分是增加还是减少
        $success = true;
        //添加新用户的情况
        if ($is_add_user && $new_score > 0){
            $success = Score::create([
                'user_id' => $user_id,
                'change_type' => 13,
                'change_num' => $new_score,
                'seq_flag' => 1,
                'change_time' => time(),
                'ref_sn' => $user_id,
                'comments' => "user|管理员调整积分+{$new_score}",
                'show_notes' => "管理员调整积分+{$new_score}",
                'table_name'=>'user',
            ]);
            return $success;
        }


        if ($old_score < $new_score) {
            //积分增加,向积分表中插入增加积分数据
            $change_num = bcsub($new_score, $old_score);
            $success = Score::create([
                'user_id' => $user_id,
                'change_type' => 13,
                'change_num' => $change_num,
                'seq_flag' => 1,
                'change_time' => time(),
                'ref_sn' => $user_id,
                'comments' => "user|管理员调整积分+{$change_num}",
                'show_notes' => "管理员调整积分+{$change_num}",
                'table_name'=>'user',
            ]);
        } elseif ($old_score > $new_score) {
            //积分减少,向积分表中插入减少积分数据
            $change_num = bcsub($old_score, $new_score);
            $success = Score::create([
                'user_id' => $user_id,
                'change_type' => 13,
                'change_num' => $change_num,
                'seq_flag' => 2,
                'change_time' => time(),
                'ref_sn' => $user_id,
                'comments' => "user|管理员调整积分-{$change_num}",
                'show_notes' => "管理员调整积分-{$change_num}",
                'table_name'=>'user',
            ]);
        }
        return $success;

    }


}
